

package com.zdsx.modules.oss.controller;

import cn.hutool.core.io.file.FileNameUtil;
import com.qcloud.cos.http.HttpMethodName;
import com.zdsx.common.annotation.LogOperation;
import com.zdsx.common.constant.Constant;
import com.zdsx.common.exception.ErrorCode;
import com.zdsx.common.page.PageData;
import com.zdsx.common.utils.DateUtils;
import com.zdsx.common.utils.JsonUtils;
import com.zdsx.common.utils.Result;
import com.zdsx.common.validator.ValidatorUtils;
import com.zdsx.common.validator.group.AliyunGroup;
import com.zdsx.common.validator.group.QcloudGroup;
import com.zdsx.common.validator.group.QiniuGroup;
import com.zdsx.modules.oss.cloud.CloudStorageConfig;
import com.zdsx.modules.oss.cloud.OSSFactory;
import com.zdsx.modules.oss.dto.OssFile;
import com.zdsx.modules.oss.entity.SysOssEntity;
import com.zdsx.modules.oss.service.SysOssService;
import com.zdsx.modules.sys.service.SysParamsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传
 *
 * @author Lr
 */
@RestController
@RequestMapping("image")
@Api(tags = "图片上传")
@AllArgsConstructor
public class OssFileController {

    private final SysParamsService sysParamsService;

    private final static String KEY = Constant.CLOUD_STORAGE_CONFIG_KEY;
    private final ValidationAutoConfiguration validationAutoConfiguration;

    @RequestMapping(value = "pre/url", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取预上传连接给前端上传")
//    @RequiresPermissions("sys:oss:all")
    public Result<Map<String, Object>> preUrl(@RequestBody @Valid OssFile ossFile) {
        //上传文件
        String fileName = ossFile.getFileName();
        String randomFileName = String.format("%s_%s", DateUtils.format(new Date(), "yyyyMMddHHmmss"), fileName);
        String url = OSSFactory.build(Constant.QCLOUD_STORAGE_CONFIG_KEY).generatePresignedUrl(randomFileName, HttpMethodName.PUT);
        String readUrl = OSSFactory.build(Constant.QCLOUD_STORAGE_CONFIG_KEY).generatePresignedUrl(randomFileName, HttpMethodName.GET);
        Map<String, Object> data = new HashMap<>(3);
        // src是前端用来上传的url，realName是保存产品的时候上传给后端的文件名
        data.put("src", url);
        data.put("readSrc", readUrl);
        data.put("realName", randomFileName);
        return new Result<Map<String, Object>>().ok(data);
    }


}